package br.sed.theenemy.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import br.sed.theenemy.business.exception.DBException;

/**
 * 
 * @author JulioCB
 * @email jcbjulio@gmail.com
 *
 */
public class AbstractDao {

	protected String query;
	Database db;
	
	public AbstractDao(){
		if ( db == null ){			
			db = Database.getInstance();			
		}
	}
	protected void closeConnection(){
		db.disconnectDatabase();
		
	}
	protected ResultSet getRS(String query) throws SQLException, DBException{
		ResultSet result = null;
		try{
			if(db.connectDatabase()){
			    result = db.getResults(query);
			    if (result==null){
			        throw new DBException("Erro de SQL");
			    }
			}
			else{
				throw new DBException("Erro de conexão");			
			}
		}
		finally{
			//db.disconnectDatabase();			
		}
		return result;		
	}
	
	protected void executeQuery(String query, String error) throws DBException{
		try{
			if(db.connectDatabase()){
				db.executeSql(query, error);
			}
			else{
			    throw new DBException("Erro de conexão");
			}
		}
		finally{
			db.disconnectDatabase();
		}
	}
	
	protected Long getId() throws DBException{
		Long id = 0l;
		try{
			if(db.connectDatabase()){
				id = db.getId();
			}
			else{
			    throw new DBException("Erro de conexão");
			}
		}
		finally{
			db.disconnectDatabase();
		}
		return id;
	}
	
}
